<template>
  <s-layout :title="pageTitle" :bgStyle="{ background: '#f0f3f8' }">
    <view class="archive-list-container">
      <view class="list-header">
        <text class="header-text">请选择需要查看或上传的档案类别</text>
      </view>
      <view v-if="loading" class="loading-state">
        <fui-loading type="col"></fui-loading>
        <text>加载中...</text>
      </view>
      <view v-else-if="archiveList.length === 0" class="empty-state">
        <fui-empty title="暂无可管理的档案类别"></fui-empty>
      </view>
      <view v-else class="list-items">
        <view
          v-for="(item, index) in archiveList"
          :key="item.id"
          class="list-item card-shadow"
          @click="goToDetailPage(item)"
        >
          <view class="item-left">
            <view
              class="item-icon-wrapper"
              :style="{ backgroundColor: getIconBgColor(index) }"
            >
              <fui-icon
                :name="getIconName(item.type)"
                color="#fff"
                size="48"
              ></fui-icon>
            </view>
            <view class="item-info">
              <text class="item-name">{{ item.name }}</text>
              <text class="item-count">已存档 {{ item.fileCount }} 项</text>
              <!-- Updated text slightly -->
            </view>
          </view>
          <view class="item-right">
            <fui-icon name="arrowright" color="#b2b2b2" size="40"></fui-icon>
          </view>
        </view>
      </view>

      
    </view>
    <view style="height: 40rpx"></view>
    <!-- Bottom padding -->
  </s-layout>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { onLoad, onUnload } from "@dcloudio/uni-app";
import sheep from "@/sheep"; // Assuming sheep is configured for API calls

interface ArchiveItem {
  id: number;
  name: string;
  order: number;
  fileCount: number;
  type: string; // e.g., 'license', 'certificate', 'report', 'other' - used for icon mapping
  allowedUploadTypes: ("image" | "video" | "file")[]; // Define allowed types for upload page
  rawData: any; // Added rawData field
}

const companyId = ref<string | null>(null);
const companyName = ref<string>("企业");
const archiveList = ref<ArchiveItem[]>([]);
const loading = ref(true);

const pageTitle = computed(() => `${companyName.value} - 企业档案`);

// Helper to parse allowed types string from backend, excluding 'video'
function parseAllowedTypes(
  typesString: string | null | undefined
): ("image" | "file")[] {
  if (!typesString) return ["image", "file"]; // Default if null/undefined
  const types = typesString.split(",").map((t) => t.trim().toLowerCase());
  const validTypes: ("image" | "file")[] = [];
  if (types.includes("image")) validTypes.push("image");
  if (types.includes("file")) validTypes.push("file");
  // Explicitly exclude 'video' or others if needed
  return validTypes.length > 0 ? validTypes : ["image", "file"]; // Fallback if only invalid types were listed
}
// --- Mock Data (Replace with API Call) ---
const fetchArchives = async (cId: string) => {
  loading.value = true;
  console.log(`Fetching archives for companyId: ${cId}`);
  try {
    const response = await sheep.$api.qy_index.archivalList({ company_id: cId });
    if (response.code === 200 && Array.isArray(response.itemList)) {
      archiveList.value = response.itemList.map(item => ({
        id: parseInt(item.ai_id),
        name: item.ai_name,
        order: parseInt(item.ai_sort),
        fileCount: parseInt(item.file_num),
        type: "license", // 默认类型
        allowedUploadTypes: ["image", "file"],
        rawData: item // 保存原始数据
      }));
    } else {
      console.error("Invalid response format:", response);
      archiveList.value = [];
    }
  } catch (error) {
    console.error("Error fetching archives:", error);
    archiveList.value = [];
    uni.showToast({ title: '网络错误，请稍后重试', icon: 'none' });
  } finally {
    loading.value = false;
  }
};

// Helper to parse allowed types string from backend (if needed)
// function parseAllowedTypes(typesString: string): ('image' | 'video' | 'file')[] {
//     if (!typesString) return ['image', 'video', 'file']; // Default or handle as needed
//     const types = typesString.split(',').map(t => t.trim().toLowerCase());
//     const validTypes: ('image' | 'video' | 'file')[] = [];
//     if (types.includes('image')) validTypes.push('image');
//     if (types.includes('video')) validTypes.push('video');
//     if (types.includes('file')) validTypes.push('file');
//     return validTypes.length > 0 ? validTypes : ['image', 'video', 'file']; // Fallback if parsing fails
// }

// --- Navigation ---
// Modified function to go to Detail page
const goToDetailPage = (item: ArchiveItem) => {
  if (!companyId.value) return;
  const allowedTypesParam = item.allowedUploadTypes.join(",");
  uni.navigateTo({
    url: `/pages/qy/archives/detail?companyId=${companyId.value}&archiveId=${
      item.id
    }&archiveName=${encodeURIComponent(
      item.name
    )}&allowedTypes=${allowedTypesParam}&rawData=${encodeURIComponent(
      JSON.stringify(item.rawData)
    )}`,
  });
};

// --- UI Helper Functions ---
const colors = [
  "#0052d9",
  "#1890ff",
  "#52c41a",
  "#fa8c16",
  "#722ed1",
  "#eb2f96",
  "#2979ff",
  "#f5222d",
];
const getIconBgColor = (index: number): string => {
  return colors[index % colors.length];
};
const getIconName = (type: string): string => {
  switch (type.toLowerCase()) {
    case "license":
      return "news";
    case "certificate":
      return "vip-card";
    case "report":
      return "file-text";
    case "contract":
      return "edit";
    case "financial":
      return "moneybag";
    case "other":
      return "folder";
    default:
      return "attach";
  }
};
// --- 事件监听函数 ---
// 创建事件监听函数
const handleDataUpdate = () => {
  console.log('列表页收到数据更新事件，准备刷新数据');
  // 使用延迟确保DOM已完全渲染
  setTimeout(() => {
    if (companyId.value) {
      console.log('开始刷新档案列表数据');
      loading.value = true; // 显示加载状态
      fetchArchives(companyId.value);
    }
  }, 100); // 短暂延迟确保DOM已渲染
};

// --- Lifecycle ---
// 在页面卸载时移除事件监听
onUnload(() => {
  console.log('页面卸载，移除事件监听');
  uni.$off('archiveDataUpdated', handleDataUpdate);
});

onLoad((options: any) => {
  // 注册事件监听
  uni.$on('archiveDataUpdated', handleDataUpdate);
  companyId.value = options.companyId || null;
  companyName.value = options.companyName
    ? decodeURIComponent(options.companyName)
    : "企业";
  if (companyId.value) {
    fetchArchives(companyId.value);
  } else {
    console.error("Missing companyId for archives list");
    uni.showToast({ title: "无法加载档案: 缺少企业ID", icon: "error" });
    loading.value = false;
    // Consider navigating back if ID is mandatory
    // setTimeout(() => uni.navigateBack(), 1500);
  }
});
</script>

<style lang="scss" scoped>
.archive-list-container {
  padding: 20rpx 30rpx;
}

.list-header {
  margin-bottom: 30rpx;
  padding: 15rpx 10rpx;
  background-color: #eaf2ff; // Light blue background
  border-radius: 12rpx;
  .header-text {
    font-size: 28rpx;
    color: #0052d9; // Theme color
    font-weight: 500;
  }
}

.loading-state,
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-top: 100rpx;
  color: #999;
  font-size: 28rpx;
  text {
    margin-top: 16rpx;
  }
}

.list-items {
  display: flex;
  flex-direction: column;
  gap: 24rpx; // Space between items
}

.list-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #fff;
  padding: 30rpx;
  border-radius: 16rpx;
  transition: transform 0.2s ease-out, box-shadow 0.2s ease-out;

  &:active {
    transform: scale(0.98);
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  }
}

.card-shadow {
  box-shadow: 0 6rpx 18rpx rgba(0, 45, 115, 0.08);
}

.item-left {
  display: flex;
  align-items: center;
  gap: 25rpx;
}

.item-icon-wrapper {
  width: 90rpx;
  height: 90rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0; // Prevent shrinking
}

.item-info {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.item-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.item-count {
  font-size: 24rpx;
  color: #888;
}

.item-right {
  flex-shrink: 0; // Prevent shrinking
  margin-left: 20rpx; // Ensure space from text
}
</style>
